package com.powernode.sqlinjection;

import com.powernode.commons.util.DbUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author Arrebol
 * @Date 2024/8/2 16:40
 * @Project jdbc
 * @Description：
 * 使用PreparedStatement向数据库表中插入一张图片
 */
public class JdbcTestBlob1 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream fis = null;
        try {
            conn = DbUtils.getConnection();
            String insertSql = "insert into t_img(name, img) VALUES (?,?)";
            ps = conn.prepareStatement(insertSql);
            ps.setString(1, "狗狗幼崽");
            //设置blob数据的时候可以传入一个输入流来读取硬盘上的文件
            fis = new FileInputStream(new File("F:\\IO\\dog\\dog.jpg"));
            ps.setBlob(2, fis);
            int count = ps.executeUpdate();
            System.out.println("插入了" + count + "条记录");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            DbUtils.close(null, ps, conn);
        }
    }
}
